from fastapi import APIRouter, Depends, HTTPException, Header
from sqlalchemy.orm import Session
from typing import Any, List
from datetime import datetime

from app.core.security import verify_token
from app.api.deps import get_db
from app.schemas.asphalt_test import AsphaltTestCreate, AsphaltTestResponse
from app.crud import asphalt_test as crud

router = APIRouter()

@router.post("/receive/asphalt-test", summary="沥青试验数据接收", response_model=dict)
async def create_asphalt_test(
    *,
    data: AsphaltTestCreate,
    db: Session = Depends(get_db),
    token: str = Depends(verify_token),
    source: str = Header(..., description="数据来源标识")
) -> Any:
    """
    接收沥青试验数据
    
    - **data**: 试验数据，包含试验基本信息和样本数据
    - **source**: 数据来源标识，需要在请求头中提供
    - **token**: 访问令牌，用于验证请求
    """
    try:
        # 转换数据为字典并添加来源信息
        data_dict = data.model_dump()
        data_dict["source"] = source
        
        # 保存数据
        result = crud.create_asphalt_test(db=db, data=data_dict)
        
        return {
            "code": 200,
            "msg": "试验数据保存成功",
            "data": {"id": result.id}
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"数据保存失败: {str(e)}"
        )

